/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.table;

import com.alibaba.fastjson2.JSONArray;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.auth.check.annotation.AuthCheckPermission;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.table.TableType;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.mapper.query.Query;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.result.DirectJsonResult;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.meta.cache.table.DynaCache;
import com.je.meta.cache.table.TableCache;
import com.je.meta.rpc.table.MetaTableRpcService;
import com.je.meta.service.common.MetaDevelopLogService;
import com.je.meta.service.table.MetaTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/je/meta/resourceTable")
public class ResourceController extends AbstractPlatformController {

    @Autowired
    private MetaDevelopLogService developLogService;
    @Autowired
    private MetaTableService tableService;
    @Autowired
    private DynaCache dynaCache;
    @Autowired
    private TableCache tableCache;
    @Autowired
    MetaTableRpcService metaTableRpcService;

    @RequestMapping(value = "/selectOne", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult selectOne(BaseMethodArgument param, HttpServletRequest request) {
        String tableCode = param.getTableCode();
        Query query = param.buildQuery();
        DynaBean bean = metaService.selectOne(tableCode, query.buildWrapper());
        if (bean != null) {
            return BaseRespResult.successResult(bean);
        } else {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.no.data.found"));
        }
    }

    @RequestMapping(value = "/getTree", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getTree(BaseMethodArgument param, HttpServletRequest request) {
        JSONTreeNode tree = manager.getTree(param, request);
        if (tree != null) {
            return BaseRespResult.successResult(DirectJsonResult.buildObjectResult(tree));
        } else {
            return BaseRespResult.successResult(DirectJsonResult.buildObjectResult("{}"));
        }
    }

    /**
     * 缓存导出表结构信息
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/exportExcel", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public File exportExcel(BaseMethodArgument param, HttpServletRequest request) throws UnsupportedEncodingException {
        String ids = getStringParameter(request, "ids");
        String fileName = getStringParameter(request, "fileName");
        if (Strings.isNullOrEmpty(ids) || Strings.isNullOrEmpty(fileName)) {
            throw new PlatformException(MessageUtils.getMessage("table.export.nameIsEmpty"), PlatformExceptionEnum.JE_CORE_EXCEL_EXP_ERROR);
        }
        return tableService.exportExcel(ids, fileName);
    }

    /**
     * 删除元数据信息，不删除物理表
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = {"/doClear"}, method = {RequestMethod.POST}, produces = {"application/json; charset=utf-8"})
    public BaseRespResult doClear(BaseMethodArgument param, HttpServletRequest request) {
        param.setTableCode("JE_CORE_RESOURCETABLE");
        //只有一个数据
        String id = getStringParameter(request, "ids");
        String result = tableService.deleteCheck(id);
        if(StringUtil.isNotEmpty(result)){
            return BaseRespResult.errorResult(result);
        }
        DynaBean dynaBean = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", id, "RESOURCETABLE_TYPE");
        if (dynaBean == null) {
            return BaseRespResult.successResult(MessageUtils.getMessage("common.delete.error"));
        }
        //int i = this.manager.doRemove(param, request);
        tableService.deleteTableMeta(id);
        if (dynaBean.get("RESOURCETABLE_TYPE").equals(TableType.MODULETABLE)) {
            return BaseRespResult.successResult(MessageUtils.getMessage("common.delete.success"));
        }
        developLogService.doDevelopLog("CLEAR", "清空表元数据", "TABLE", "资源表", dynaBean.getStr("RESOURCETABLE_TABLENAME"), dynaBean.getStr("RESOURCETABLE_TABLECODE"), dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"), dynaBean.getStr("SY_PRODUCT_ID"));
        return BaseRespResult.successResult(MessageUtils.getMessage("table.clear.success"));
    }

    /**
     * 资源表基础信息保存更新
     *
     * @param param
     * @param request
     * @return
     */
    @Override
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String resourcetableTablecode = getStringParameter(request, "RESOURCETABLE_TABLECODE");
        String resourcetableTablename = getStringParameter(request, "RESOURCETABLE_TABLENAME");
        if (StringUtil.isEmpty(resourcetableTablecode)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.code.canotEmpty"));
        }
        if (StringUtil.isEmpty(resourcetableTablename)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.name.canotEmpty"));
        }
        DynaBean tableInfo = metaService.selectOneByPk("JE_CORE_RESOURCETABLE", dynaBean.getStr("JE_CORE_RESOURCETABLE_ID"));
        if (tableService.checkTableCodeExcludeCode(dynaBean)) {
            if (!Strings.isNullOrEmpty(tableInfo.getStr("RESOURCETABLE_TYPE")) && tableInfo.getStr("RESOURCETABLE_TYPE").equals("MODULE")) {
                return BaseRespResult.errorResult(MessageUtils.getMessage("module.code.repeat"));
            }
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.code.repeat"));
        }
        DynaBean updated = tableService.doUpdate(dynaBean);
        return BaseRespResult.successResult(updated, MessageUtils.getMessage("common.save.success"));
    }

    /**
     * 真实物理删除资源表
     *
     * @param param
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/doHardDelete", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doHardDelete(BaseMethodArgument param, HttpServletRequest request) {
        String ids = param.getIds();
        if (StringUtil.isEmpty(ids)) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("common.params.illegal"));
        }

        String result =tableService.doHardDelete(ids);
        if (StringUtil.isNotEmpty(result)) {
            return BaseRespResult.errorResult(result);
        }
        return BaseRespResult.successResult("1000", "", MessageUtils.getMessage("common.delete.success"));
    }

    /**
     * 导入表
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/import", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult importTable(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String resourcetableTablecode = getStringParameter(request, "RESOURCETABLE_TABLECODE");
        String resourcetableTablename = getStringParameter(request, "RESOURCETABLE_TABLENAME");
        String syParent = getStringParameter(request, "SY_PARENT");
        String productId = getStringParameter(request, "SY_PRODUCT_ID");
        if (StringUtil.isEmpty(productId)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("framework.product.id.notEmpty"));
        }
        if (StringUtil.isEmpty(resourcetableTablecode)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.code.canotEmpty"));
        }
        if (StringUtil.isEmpty(syParent)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.module.canotempty"));
        }
        DynaBean table = metaService.selectOne("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder().eq("RESOURCETABLE_TABLECODE", dynaBean.getStr("RESOURCETABLE_TABLECODE")));
        if (table != null) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.code.exits"));
        } else {
            dynaBean.set("RESOURCETABLE_IMPORT", 1);
            dynaBean.set("RESOURCETABLE_ISCREATE", 0);
            dynaBean.set("RESOURCETABLE_ISUSEFOREIGNKEY", 0);
            dynaBean.set("SY_DISABLED", 0);
            dynaBean.setStr(BeanService.KEY_TABLE_CODE, "JE_CORE_RESOURCETABLE");
            dynaBean.set("RESOURCETABLE_TABLENAME", resourcetableTablename);
            tableService.impTable(dynaBean);
            return BaseRespResult.successResult("1000", "", MessageUtils.getMessage("common.import.success"));
        }
    }

    /**
     * 清空表结构的缓存
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/clearCache", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult clearCache(BaseMethodArgument param, HttpServletRequest request) {
        String resourceTableCode = getStringParameter(request, "RESOURCETABLE_TABLECODE");
        if (StringUtil.isEmpty("resourceTableCode")) {
            return BaseRespResult.errorResult("1000", "", MessageUtils.getMessage("table.code.canotEmpty"));
        }
        List<String> list = metaTableRpcService.clearTableCache(resourceTableCode);
        for (String str : list) {
            metaService.clearMyBatisTableCache(str);
        }
        return BaseRespResult.successResult("1000", "", MessageUtils.getMessage("common.clear.success"));
    }

    /**
     * 清空所有缓存
     *
     * @param param
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/clearCacheAll", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult clearCacheAll(BaseMethodArgument param) {
        tableCache.clear();
        dynaCache.clear();
        return BaseRespResult.successResult("1000", "", MessageUtils.getMessage("common.clearCache.success"));
    }

    /**
     * 首页加载
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/loadHome", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult loadHome(BaseMethodArgument param, HttpServletRequest request) {
        // TODO 目前首页来源是在架构管理的产品里面维护的，目前不知道放什么，暂时不实现
        return BaseRespResult.successResult("");
    }

    /**
     * 查看关系视图
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/selectRelation", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult selectRelation(BaseMethodArgument param, HttpServletRequest request) {
        String pkValue = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
        if (StringUtil.isEmpty(pkValue)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.id.canotEmpty"));
        }
        DynaBean dynaBean = tableService.selectRelation(pkValue);
        return BaseRespResult.successResult(dynaBean);
    }

    /**
     * 转移模块表等操作
     */
    /*@RequestMapping(value = "/move", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult move(BaseMethodArgument param, HttpServletRequest request) {
        String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
        String toResourceId = getStringParameter(request, "toResourceId");
        String place = getStringParameter(request, "place");
        if (StringUtil.isEmpty(resourceId)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.transfer.source.notEmpty"));
        }
        if (StringUtil.isEmpty(toResourceId)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.transfer.target.notEmpty"));
        }
        if (StringUtil.isEmpty(place)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.transfer.target.placePosition"));
        }
        DynaBean dynaBean = tableService.move(resourceId, toResourceId, place);
        return BaseRespResult.successResult(dynaBean);
    }*/

    /**
     * 历史留痕加载操作
     *
     * @param param
     * @param request
     * @return
     */

    public BaseRespResult loadHistoricalTracesA(BaseMethodArgument param, HttpServletRequest request) {
        String resourceId = getStringParameter(request, "JE_CORE_RESOURCETABLE_ID");
        if (StringUtil.isEmpty(resourceId)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("table.id.canotEmpty"));
        }
        List<Map<String, Object>> resultList = tableService.loadHistoricalTraces(resourceId);
        return BaseRespResult.successResultPage(resultList, (long) resultList.size());
    }

    /**
     * 历史留痕加载操作
     *
     * @param param
     * @param request
     * @return
     */
    @AuthCheckPermission(value = "pc-plugin-JE_CORE_TABLE-show")
    @RequestMapping(value = "/loadHistoricalTraces", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult loadHistoricalTraces(BaseMethodArgument param, HttpServletRequest request) {
        Page page = this.manager.load(param, request);
        if (page == null) {
            return BaseRespResult.successResultPage(Lists.newArrayList(), 0L);
        }
        List<Map<String, Object>> records = page.getRecords();
        records.forEach(eachData -> {
            String tableXgnrStr = String.valueOf(eachData.get("TABLETRACE_XGNRJSON"));
            JSONArray tableXgnrJon = JSONArray.parseArray(tableXgnrStr);
            eachData.put("TABLETRACE_XGNRJSON", tableXgnrJon);
        });
//        List<Map<String, Object>> resultList = tableService.loadHistoricalTraces(resourceId);
        return BaseRespResult.successResultPage(records, (long) page.getTotal());
    }

}
